<?php


namespace app\cms\community\lib\Query;


use app\cms\model\formModel;
use app\community\elasticSearch\lib\buildQueryParams;
use app\community\elasticSearch\lib\QuerySearch;
use iflow\Response;
use think\Model;

class ElasticsearchQuery extends Model {

    use Elasticsearch;

    // 标题字段
    protected string $titleField;

    // 搜索关键词
    protected string $keyword = '';

    /**
     * 排序字段
     * @var array|string[][]
     */
    protected array $sort = [
        'create_time' => [
            'order' => 'desc'
        ]
    ];

    protected int $formId = 0;
    protected array $formModel;

    /**
     * 执行查询
     * @return Response
     */
    public function ElasticsearchQuery(): Response {

        $this->setIndexType();

        $this->modelName = $this->formModel['form_name'] ?? $this->indexName;
        $this->titleField = $this->formModel['title_field'] ?? $this->titleField;

        $queryParams = new buildQueryParams();
        $queryParams -> setField(
            $this->titleField,
            $this->keyword
        )-> setHighlight([
            'pre_tags' => ['<em style="color: #f25d8e; font-style: normal;font-weight: 400;">'],
            'post_tags' => ["</em>"],
            'fields' => [
                $this->titleField => new \stdClass()
            ]
        ]) -> setSort($this->sort);
        $query = (new QuerySearch('default'))
            -> setIndexName($this->modelName)
            -> setTypeName($this->elsTypeName)
            -> query(
                $queryParams
            );
        return message() -> success('查询成功', $query -> getRows(), [
            'count' => $query -> getTotal(),
            'page' => $query -> getLastPage(),
            'form_id' => $this->formId,
            'title_field' => $this->formModel['title_field']
        ]);

    }

    /**
     * @param string $keyword
     * @return static
     */
    public function setKeyword(string $keyword): static
    {
        $this->keyword = $keyword;
        return $this;
    }

    /**
     * @param int $formId
     * @return static
     */
    public function setFormId(int $formId): static
    {
        $this->formId = $formId;
        $this->formModel = formModel::getForm($formId) ?: [];
        return $this;
    }

    /**
     * @param array $sort
     * @return elasticsearchQuery
     */
    public function setSort(array $sort): static {
        $this->sort = $sort;
        return $this;
    }
}